<template>
	<picker @change="pickerChange" :range="data" :range-key="textField" :value="valueIndex">
		<view class="uni-select">
			<view>{{placeholderText}}</view>
			<uni-icons type="arrowdown"></uni-icons>
		</view>
	</picker>
</template>

<script>
	/**
	 * DownSelect 下拉选择组件
	 * @property {String} placeholder  未选择提示信息
	 * @property {String} textField  显示文本字段
	 * @property {Array} data  数据源
	 * @property {String|Object} value  绑定的值,使用value.sync更新值
	 * @event {Function} change  选中发生变化触发
	 */
	export default {
		name: 'UniDownSelect',
		props: {
			placeholder: String,
			textField: String,
			valueField: String,
			data: Array,
			value: ''
		},
		computed: {
			placeholderText() {
				let value;
				let text;
				if (this.textField) {
					value = this.detail[this.valueField]
					text = this.detail[this.textField]
				} else {
					value = text = this.detail
				}
				return (value && value != '') ? text : this.placeholder
			},

			valueIndex() {
				if (this.value) {
					let valueIndex;
					if (this.textField) {
						valueIndex = this.data.findIndex((item) => {
							return item[this.valueField] == this.value[this.valueField]
						})
					} else {
						valueIndex = this.data.findIndex((item) => {
							return item == this.value
						})
					}
					return valueIndex
				}
			}
		},
		data() {
			return {
				detail: this.value
			}
		},
		methods: {
			pickerChange(e) {
				this.detail = this.data[e.detail.value]
				this.$emit('update:value', this.detail)
				this.$emit('change', this.detail) //抛出
			}
		}
	}
</script>

<style>
	/*下拉框*/
	.uni-select {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 5px 8px;
		border: 1px solid #E5E5E5;
		border-radius: 4px;
		box-sizing: border-box;
		cursor: pointer;
	}
</style>
